package com.senior.sendmessage.controller.wechat;

import com.senior.sendmessage.service.wechat.WeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Baijl
 * @version 0.0.1
 * @date 2021-11-11 12:47
 * @description TODO
 */
@RestController
@Slf4j
@RequiredArgsConstructor
public class WeChatController {
    private final WeChatService weChatService;
    private final WxMpService wxMpService;


    /**
     * 验证
     *
     * @param msgSignature 签名
     * @param timeStamp    时间戳
     * @param nonce        现时标志
     * @param echoStr      回声str
     * @return {@link String}
     */
    @GetMapping(value = "/wechat")
    public String verification(@RequestParam("signature") final String msgSignature,
                               @RequestParam("timestamp") final String timeStamp,
                               @RequestParam("nonce") final String nonce,
                               @RequestParam("echostr") final String echoStr) {
        final boolean b = wxMpService.checkSignature(timeStamp, nonce, msgSignature);
        if (b) {
            return echoStr;
        }
        return "msgSignature";
    }

    /**
     * 被动回复消息
     *
     * @param request 请求
     * @return {@link String}
     * @throws Exception 异常
     */
    @PostMapping(value = "/wechat", produces = MediaType.APPLICATION_XML_VALUE)
    public String receiveMsg(final HttpServletRequest request) throws Exception {
        return weChatService.receiveMsg(request);

    }

    /**
     * 群发接口
     *
     * @throws WxErrorException wx错误异常
     */
//    @Scheduled(cron = "0 0 0/1 * * ?")
    @GetMapping("mass")
    public void mass() throws WxErrorException {
        weChatService.mass();
    }

}
